<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Auth\Role;
use App\Models\Auth\User;
use App\Models\Common\ApiResponse;
use App\Models\Common\BaseModel;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Builder;

class RoleController extends Controller
{

    public $name = '角色管理';

    public function index(Request $request)
    {
        $user = admin();
        $more = $request->post();

        $page = intval($request->get('page') ?: 1);
        $perPage = intval($request->get('per_page') ?: 10);

        $baseQuery = Role::query();

//        switch ($user->identity) {
//            case User::IDENTITY_SYSTEM:
//                if (sourceMerchant()) {
//                    $baseQuery->where('merchant_id', getMerchantID());
//                } else {
//                    if (sourceParkingLot()) {
//                        $baseQuery->where('parking_lot_id', getParkingLotID());
//                    } else {
//                        $baseQuery->where('parking_lot_id', '')->where('merchant_id', '');
//                    }
//                }
//                break;
//            case User::IDENTITY_STATION:
//            case User::IDENTITY_PARKING_LOT:
//                $baseQuery->where('parking_lot_id', getParkingLotID());
//                break;
//            case User::IDENTITY_MERCHANT:
//                $baseQuery->where('merchant_id', getMerchantID());
//                break;
//            default:
//                throw new \InvalidArgumentException('无查看角色的权限');
//        }

        // 仅展示自己创建的
        $baseQuery->where('user_id', $user->id);

        self::searchQuery($baseQuery, $more);

        $roles = BaseModel::getList($baseQuery, $page, $perPage);

        return ApiResponse::return('', $roles);
    }

    private function searchQuery(Builder $query, array $input = [])
    {
        $name = Arr::get($input, 'name');
        if (null !== $name) {
            $query->where('name', 'like', '%'.$name.'%');
        }

    }

    public function all(Request $request)
    {
        $user = admin();
        $baseQuery = Role::query();

//        switch ($user->identity) {
//            case User::IDENTITY_SYSTEM:
//                if (sourceMerchant()) {
//                    $baseQuery->where('merchant_id', getMerchantID());
//                } else {
//                    if (sourceParkingLot()) {
//                        $baseQuery->where('parking_lot_id', getParkingLotID());
//                    } else {
//                        $baseQuery->where('parking_lot_id', '')->where('merchant_id', '');
//                    }
//                }
//                break;
//            case User::IDENTITY_STATION:
//            case User::IDENTITY_PARKING_LOT:
//                $baseQuery->where('parking_lot_id', getParkingLotID());
//                break;
//            case User::IDENTITY_MERCHANT:
//                $baseQuery->where('merchant_id', getMerchantID());
//                break;
//            default:
//                throw new \InvalidArgumentException('无查看角色的权限');
//        }

        // 仅展示自己创建的
        $baseQuery->where('user_id', $user->id);

        return ApiResponse::return('', $baseQuery->get(['id', 'name']));
    }

    public function store(Request $request)
    {
        $this->admin = $user = admin();
        $this->logContent = '编辑角色';
        $permissionNames = array_unique(array_filter(explode(',', $request->get('permission_names'))));

//        \Log::info('编辑角色', $request->post());

        if ($permissionNames) {
            $adminPermissions = $user->_permissions;

            foreach ($permissionNames as $permissionName) {
                if (!in_array($permissionName, $adminPermissions, true)) {
                    throw new \InvalidArgumentException('不可分配超出账号权限范围的权限'.$permissionName);
                }
            }
        } else {
            $permissionNames = [];
        }

        if ($id = $request->get('id')) {
            $role = Role::findOrFail($id);

            $userRoleIDs = $user->roles()->pluck('id')->toArray();
            if (in_array($id, $userRoleIDs)) {
                throw new \InvalidArgumentException('不可修改当前账号所属角色');
            }

        } else {
            $role = new Role();
            $role->id = Str::orderedUuid()->toString();
            $role->user_id = $user->id;
        }

        $name = $request->get('name');
        if (is_numeric($name)) {
            throw new \InvalidArgumentException('名称不可为纯数字');
        }

        $role->fill($request->only(['name']));

        switch ($user->identity) {
            case User::IDENTITY_SYSTEM:
                if (sourceMerchant()) {
                    $this->parkingLotID = getParkingLotID();
                    $role->parking_lot_id = '';
                    $role->merchant_id = getMerchantID();
                } else {
//                    if (sourceParkingLot()) {
//                        $this->parkingLotID = $role->parking_lot_id = getParkingLotID();
//                    }
                }
                break;
            case User::IDENTITY_AGENT:
            case User::IDENTITY_PARKING_LOT:
                if ($parkingLot = $user->parkingLots()->first()) {
                    $this->parkingLotID = $parkingLot->id;
                }
                break;
            case User::IDENTITY_STATION:
//                $this->parkingLotID = $role->parking_lot_id = getParkingLotID();
                break;
            case User::IDENTITY_MERCHANT:
                $this->parkingLotID = getParkingLotID();
                $role->parking_lot_id = '';
                $role->merchant_id = getMerchantID();
                break;
            default:
                throw new \InvalidArgumentException('没有编辑角色的权限');
        }

        $role->parking_lot_id = strval($role->parking_lot_id);
        $role->merchant_id = strval($role->merchant_id);

        if (!$role->name) {
            throw new \InvalidArgumentException('角色名称不能为空');
        }

        if (Role::where('name', $role->name)->where('id', '<>', $role->id)->exists()) {
            throw new \InvalidArgumentException('角色名称已被占用，请更换');
        }

        if ($request->exists('remark')) {
            $role->remark = $request->get('remark') ?: '';
        }

        if (\DB::transaction(function () use ($role, $permissionNames) {
            $role->save();
            $role->syncPermissions($permissionNames);
            return true;
        })) {
            return ApiResponse::return('', ['id' => $role->id]);
        }

        return ApiResponse::return('', null, ApiResponse::RESP_CODE_FAILURE);
    }

    public function show($id)
    {
        $role = Role::with(['permissions'])->findOrFail($id);
        return ApiResponse::return('', $role);
    }

    public function destroy($id)
    {
        $this->admin = $user = admin();
        $this->logContent = '删除角色';
        $baseQuery = Role::query();
        if (sourceMerchant()) {
            $this->parkingLotID = getParkingLotID();
            $baseQuery->where('merchant_id', getMerchantID());
        } else {
            if (sourceParkingLot()) {
                $this->parkingLotID = getParkingLotID();
                $baseQuery->where('parking_lot_id', getParkingLotID());
            } else {
                $baseQuery->where('parking_lot_id', '')->where('merchant_id', '');
            }
        }

        if (!$role = $baseQuery->find($id)) {
            return ApiResponse::return();
        }

        $userIds = \DB::table('model_has_roles')->where('role_id', $id)->pluck('model_id');
        if ($userIds->count()) {
            if (User::whereIn('id', $userIds)->exists()) {
                return ApiResponse::fail('存在已绑定该角色的用户，不可删除');
            }
        }

        if (\DB::transaction(function () use ($role) {
            $role->syncPermissions([]);
            return $role->delete();
        })) {
            return ApiResponse::return();
        }

        return ApiResponse::return('', '', ApiResponse::RESP_CODE_FAILURE);
    }
}
